﻿using BW.Mes.WinForms.BasicData;
using DevExpress.XtraEditors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static BW.Mes.WinForms.Process.ProcessDataForm;

namespace BW.Mes.WinForms.Production.Order
{
    public partial class AddOrederForm : DevExpress.XtraEditors.XtraForm
    {
        private readonly HttpClient _httpClient;
        private readonly string _apiBaseUrl = "https://localhost:7274";
        private readonly string _apiProcessUrl = "https://localhost:7222";


        public AddOrederForm()
        {
            InitializeComponent();

            // 添加单选框的CheckedChanged事件处理
            on_off.CheckedChanged += On_off_CheckedChanged;


            // 初始化字段
            _httpClient = new HttpClient();
            _apiProcessUrl = "https://localhost:7222"; // 替换为您的实际API基础URL
            _apiBaseUrl = "https://localhost:7274";
            ShowProcess();

        }
        #region 照片上传

        private async void Photo_Click(object sender, EventArgs e)
        {
            // 调用 XtraOpenFileDialog
            xtraOpenFileDialog1.Filter = "所有文件 (*.*)|*.*"; // 设置筛选器
            if (xtraOpenFileDialog1.ShowDialog() == DialogResult.OK)
            {
                // 用户选了文件，可获取路径
                string filePath = xtraOpenFileDialog1.FileName;
                // 显示选择的文件路径
                Img.Text = filePath;

                try
                {
                    // 上传文件并获取返回的URL
                    string fileUrl = await UploadFileAsync(filePath);
                    if (!string.IsNullOrEmpty(fileUrl))
                    {
                        // 将返回的URL保存到Img属性
                        Img.Text = fileUrl;
                        XtraMessageBox.Show("文件上传成功！");
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBox.Show("文件上传失败：" + ex.Message);
                }
            }
        }

        /// <summary>
        /// 上传文件到服务器
        /// </summary>
        /// <param name="filePath">本地文件路径</param>
        /// <returns>返回服务器存储的文件URL</returns>
        private async Task<string> UploadFileAsync(string filePath)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://localhost:7223");

                    // 创建MultipartFormDataContent用于上传文件
                    using (var content = new MultipartFormDataContent())
                    {
                        // 读取文件内容
                        var fileContent = new ByteArrayContent(File.ReadAllBytes(filePath));

                        // 获取文件名和文件类型
                        string fileName = Path.GetFileName(filePath);
                        string fileExtension = Path.GetExtension(filePath);

                        // 根据文件扩展名设置内容类型
                        switch (fileExtension.ToLower())
                        {
                            case ".jpg":
                            case ".jpeg":
                                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
                                break;
                            case ".png":
                                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
                                break;
                            case ".pdf":
                                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                                break;
                            default:
                                fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                                break;
                        }

                        // 添加文件到请求内容
                        content.Add(fileContent, "file", fileName);

                        // 发送POST请求到文件上传API
                        var response = await client.PostAsync("/api/ProduceModel/UploadWorkorderImage", content);

                        // 检查响应是否成功
                        if (response.IsSuccessStatusCode)
                        {
                            // 读取响应内容
                            string responseContent = await response.Content.ReadAsStringAsync();
                            // 解析JSON响应以获取文件URL
                            var result = JsonConvert.DeserializeObject<FileUploadResponse>(responseContent);
                            return result.FileUrl;
                        }
                        else
                        {
                            throw new Exception($"服务器返回错误：{response.StatusCode} - {response.ReasonPhrase}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"上传文件时发生错误：{ex.Message}", ex);
            }
        }

        /// <summary>
        /// 文件上传响应类
        /// </summary>
        public class FileUploadResponse
        {
            /// <summary>
            /// 上传后的文件URL
            /// </summary>
            public string FileUrl { get; set; }

            /// <summary>
            /// 是否成功
            /// </summary>
            public bool Success { get; set; }

            /// <summary>
            /// 消息
            /// </summary>
            public string Message { get; set; }
        }
        #endregion




        /// <summary>
        /// 添加工单的方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AddOrdeAction_Click(object sender, EventArgs e)
        {

            //if (Client.EditValue == null)
            //{
            //    XtraMessageBox.Show("请选择客户");
            //    return;
            //}

            if (Line.EditValue == null)
            {
                XtraMessageBox.Show("请选择产线");
                return;
            }

            var model = new OrderForm
            {
                Code = Code.Text,
                ProductionType = ProductionType.Text,
                Client = !string.IsNullOrWhiteSpace(Client.Text) && long.TryParse(Client.Text, out long clientId) ? clientId : 0,
                Masterdata = Masterdata.Text,
                // 使用EditValue获取选中的ID值
                Line = Line.EditValue != null ? Convert.ToInt64(Line.EditValue) : 0,
                ProductionCount = !string.IsNullOrWhiteSpace(ProductionCount.Text) && int.TryParse(ProductionCount.Text, out int count) ? count : 0,
                Progress = Progress.Text,
                BeginTime = BeginTime.DateTime,
                EndTime = EndTime.DateTime,
                Whether = Whether.Text,
                Img = Img.Text,
                ProductionDesc = ProductionDesc.Text,
                CreatedBy = "admin",
            };

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://localhost:7223");

                var json = JsonConvert.SerializeObject(model);

                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await client.PostAsync("/api/ProduceModel/AddWorkorder", content);

                if (response.IsSuccessStatusCode)
                {
                    XtraMessageBox.Show("添加成功！");
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
                else
                {
                    XtraMessageBox.Show("添加失败：" + response.ReasonPhrase);
                }
            }
        }
        //下拉
       

        private async Task ShowProcess()
        {
            try
            {
                HttpResponseMessage response = await _httpClient.GetAsync($"{_apiProcessUrl}/api/ProcessModel/ShowProcess");
                response.EnsureSuccessStatusCode();


                string responseBody = await response.Content.ReadAsStringAsync();
                var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

                if (jsonObject["pagingData"] != null)
                {
                    string dataJson = jsonObject["pagingData"].ToString();
                    var process = JsonConvert.DeserializeObject<List<ProcessModel>>(dataJson);

                    // 设置数据源
                    Line.Properties.DataSource = process;
                    // 在加载产线数据时
                    Line.Properties.ValueMember = "Id";  // 数据源中的主键字段名
                    Line.Properties.DisplayMember = "ProcessName";  // 数据源中的显示文本字段名
                    Line.Properties.NullText = "请选择所属产线";

                    // 配置GridLookUpEdit的列 - 使用正确的方式
                    if (Line.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
                    {
                        // 清除现有列
                        gridView.Columns.Clear();

                        // 添加产线名称列
                        DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
                        nameColumn.Caption = "产线名称";
                        nameColumn.FieldName = "ProcessName";
                        nameColumn.Visible = true;
                        nameColumn.VisibleIndex = 0;

                        // 可选：设置列宽
                        nameColumn.Width = 150;

                        // 添加列到网格视图
                        gridView.Columns.Add(nameColumn);

                        // 禁用网格视图的分组面板
                        gridView.OptionsView.ShowGroupPanel = false;

                        // 设置行焦点样式
                        gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

                        // 禁用单元格焦点外观
                        gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"加载产线数据失败: {ex.Message}", "错误");
                throw;
            }

        }
        #region 获取所有客户
        /// 获取所有客户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Client_Click(object sender, EventArgs e)
        {
            //await ShowClient();
        }

        //private async Task ShowClient()
        //{
        //    try
        //    {
        //        HttpResponseMessage response = await _httpClient.GetAsync($"{_apiBaseUrl}/api/Customer/GetCustomer");
        //        response.EnsureSuccessStatusCode();


        //        string responseBody = await response.Content.ReadAsStringAsync();
        //        var jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseBody);

        //        if (jsonObject["pageDatas"] != null)
        //        {
        //            string dataJson = jsonObject["pageDatas"].ToString();
        //            var process = JsonConvert.DeserializeObject<List<CustomerModel>>(dataJson);

        //            // 设置数据源
        //            Client.Properties.DataSource = process;
        //            // 在加载产线数据时
        //            Client.Properties.ValueMember = "Id";  // 数据源中的主键字段名
        //            Client.Properties.DisplayMember = "CustomerName";  // 数据源中的显示文本字段名
        //            Client.Properties.NullText = "请选择所属客户";

        //            // 配置GridLookUpEdit的列 - 使用正确的方式
        //            if (Client.Properties.PopupView is DevExpress.XtraGrid.Views.Grid.GridView gridView)
        //            {
        //                // 清除现有列
        //                gridView.Columns.Clear();

        //                // 添加产线名称列
        //                DevExpress.XtraGrid.Columns.GridColumn nameColumn = new DevExpress.XtraGrid.Columns.GridColumn();
        //                nameColumn.Caption = "客户名称";
        //                nameColumn.FieldName = "CustomerName";
        //                nameColumn.Visible = true;
        //                nameColumn.VisibleIndex = 0;

        //                // 可选：设置列宽
        //                nameColumn.Width = 150;

        //                // 添加列到网格视图
        //                gridView.Columns.Add(nameColumn);

        //                // 禁用网格视图的分组面板
        //                gridView.OptionsView.ShowGroupPanel = false;

        //                // 设置行焦点样式
        //                gridView.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;

        //                // 禁用单元格焦点外观
        //                gridView.OptionsSelection.EnableAppearanceFocusedCell = false;
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        XtraMessageBox.Show($"加载客户数据失败: {ex.Message}", "错误");
        //        throw;
        //    }

        //}
        #endregion


        /// <summary>
        /// 实体类
        /// </summary>
        public class OrderForm
        {
            /// <summary>
            /// 编码
            /// </summary>
            public string Code { get; set; }
            /// <summary>
            /// 类型  （正常、自建工单）
            /// </summary>
            public string ProductionType { get; set; }
            /// <summary>
            /// 客户  （外键）
            /// </summary>
            public long Client { get; set; }
            /// <summary>
            /// 产品主数据
            /// </summary>
            public string Masterdata { get; set; }
            /// <summary>
            /// 产线 （外键）
            /// </summary>
            public long Line { get; set; }
            /// <summary>
            /// 工序进度
            /// </summary>
            public string Progress { get; set; }
            /// <summary>
            /// 数量
            /// </summary>
            public int ProductionCount { get; set; }
            /// <summary>
            /// 开始时间
            /// </summary>
            public DateTime BeginTime { get; set; }
            /// <summary>
            /// 结束时间
            /// </summary>
            public DateTime EndTime { get; set; }
            /// <summary>
            /// 是否允许有跳工序
            /// </summary>
            public string Whether { get; set; }
            /// <summary>
            /// 上传文件
            /// </summary>
            public string Img { get; set; }
            /// <summary>
            /// 备注
            /// </summary>
            public string ProductionDesc { get; set; }

            /// <summary>
            /// 添加人
            /// </summary>
            public string CreatedBy { get; set; }
        }
        /// <summary>
        /// 单选框状态变化事件处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void On_off_CheckedChanged(object sender, EventArgs e)
        {
            if (on_off.Checked)
            {
                // 勾选时，生成以MO开头+年月日+四位随机数的编码
                string datePrefix = DateTime.Now.ToString("yyyyMMdd");
                string randomNumber = GenerateRandomNumber(4);
                Code.Text = $"MO{datePrefix}{randomNumber}";

                // 设置Code文本框为不可编辑且不可选中
                Code.Properties.ReadOnly = true;
                Code.Enabled = false;  // 禁用控件，使其不可选中
            }
            else
            {
                // 未勾选时，清空文本框
                Code.Text = string.Empty;

                // 设置Code文本框为可编辑
                Code.Properties.ReadOnly = false;
                Code.Enabled = true;   // 启用控件
            }
        }
        // 生成指定位数的随机数字字符串
        private string GenerateRandomNumber(int digits)
        {
            Random random = new Random();
            int minValue = (int)Math.Pow(10, digits - 1);
            int maxValue = (int)Math.Pow(10, digits) - 1;
            int randomNum = random.Next(minValue, maxValue);
            return randomNum.ToString();
        }

        
    }
}